<template>
	<div>
		<div>
			<div class="search_row">
				<div>
					<el-input class="input_top" @input="filterg" v-model="search" style="width: 220px;height: 36px;"
						placeholder="请输入景点名称">
						<template #prefix>
							<el-icon>
								<Search />
							</el-icon>
						</template>
					</el-input>
					<el-button @click="searchs()" type="primary" style="width: 55px;height: 35px;margin-left: 10px;">
						<el-icon>
							<Search />
						</el-icon>
						查询</el-button>
					<el-button type="warning" class="button" style="width: 55px;height: 35px;margin-left: 10px"
						@click="resets()">
						<el-icon>
							<RefreshRight />
						</el-icon>
						重置
					</el-button>
				</div>
				<el-button type="primary" @click="add" style="width: 55px;height: 35px;">新增</el-button>
			</div>
			<div style="padding-bottom: 10px;">
				<el-button @click="deleList" style="height: 35px;" type="danger">批量删除</el-button>
			</div>
			<el-table lazy :load="loadTableData" row-key="id" v-el-table-infinite-scroll="handleTableScroll"
				:infinite-scroll-distance="100" @selection-change="handleSelectionChange" ref="multipleTableRef"
				:data="Data_Img.slice((currentPage - 1) * pageSize, currentPage * pageSize)" border style="width: 100%"
				:cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" stripe>
				<el-table-column type="selection" width="55" />
				<el-table-column fixed prop="id" label="序号" width="70" />
				<el-table-column prop="name" label="名称" />
				<el-table-column prop="cover" label="封面图片">
					<template #default="scope">
						<div>
							<el-image style="width: 60px; height: 60px"
								:src="testName + scope.row.cover" :zoom-rate="1.2" :max-scale="7"
								:testName-scale="0.2" :preview-src-list="[testName + scope.row.cover]"
								:initial-index="4" fit="cover" preview-teleported />

						</div>
					</template>
				</el-table-column>



				<!-- <el-table-column prop="introduce" show-overflow-tooltip label="介绍" /> -->
				<el-table-column prop="pageviews" width="110" label="浏览量" />
				<el-table-column prop="create_time" label="创建时间" />
				<el-table-column fixed="right" label="操作" width="200">
					<template #default="scope">
						<div class="handle">
							<el-button type="primary" @click="edit(scope.row)"
								style="width: 55px;height: 35px;">编辑</el-button>
							<el-button type="danger" style="width: 55px;height: 35px;"
								@click="deletes(scope.row)">删除</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<div class="paging">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
					:small="small" :disabled="disabled" background layout="total, sizes, prev, pager, next, jumper"
					:total="Data_Img.length" />
			</div>
			<div></div>
		</div>
		<!-- 新增弹窗 -->
		<el-dialog v-model="dialogVisible">
			<img style="width: 100%; height: 100%" w-full :src="dialogImageUrl" alt="Preview Image" />
		</el-dialog>
		<el-dialog v-model="dialogVisiblet">
			<img style="width: 100%; height: 100%" w-full :src="dialogImageUrlt" alt="Preview Image" />
		</el-dialog>
		<!-- 新增弹出框 -->
		<el-dialog v-model="dialogTableVisible" z-index="4" @close="close(ruleFormRef)" :title="disableds ? '添加' : '编辑'"
			width="50vw">
			<el-form ref="ruleFormRef" style="width:100%" :model="ruleForm" status-icon :rules="rules"
				label-width="auto" class="demo-ruleForm">
				<el-form-item label="景点名称" prop="name">
					<el-input v-model="ruleForm.name" style="width: 100%" placeholder="请输入景点名称" autocomplete="off" />
				</el-form-item>
				<!-- 单图封面图片 -->
				<el-form-item prop="covers" label="封面图片">
					<el-upload list-type="picture-card" accept=".jpeg,.png,.jpg,.bmp,.gif"
						:on-preview="handlePictureCardPreviewt" :on-remove="handleRemovet" :file-list="fileListt"
						:before-upload="beforeAvatarUploadt">
						<el-icon>
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>

				<!-- 多图片上传   -->
				<!-- <el-form :model="form"> -->

				<el-form-item prop="img" label="景点图片">
					<!-- <div style="display: flex;"> -->
					<!-- <div style="width: 80px;"><span style="color: red;">*</span>景点图片</div> -->
					<el-upload list-type="picture-card" accept=".jpeg,.png,.jpg,.bmp,.gif" :on-exceed="exceed_li"
						:on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="fileList"
						:on-change="handleChange" :on-success="handleSuccess" :before-upload="beforeUpload"
						:auto-upload="false" :limit="4">
						<el-icon>
							<Plus />
						</el-icon>
					</el-upload>
					<!-- </div> -->
				</el-form-item>
				<div style="color: red;font-size: 12px;margin-left: 15%;padding-bottom: 2%;">*最多上传四张图片</div>
				<!-- <div id="exttas" >请上传图片</div> -->
				<el-form-item label="景点介绍" prop="introduce">
					<!-- <el-input v-model="ruleForm.introduce" style="width: 430px" placeholder="请输入景点介绍" /> -->
					<vue-ueditor-wrap v-model="ruleForm.introduce" :config="editorConfig"
						editor-id="editor-demo-01"></vue-ueditor-wrap>

				</el-form-item>
				<!-- </el-form> -->
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
					<el-button @click="closes(ruleFormRef)">取消</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 删除弹窗 -->
		<el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
			<div style="font-size: 16px">确认删除该景点吗?</div>
			<span slot="footer" style="display: flex; justify-content: space-between" class="dialog-footer">
				<div></div>
				<div style="height: 30px;margin-top: 20px;">
					<el-button @click="centerDialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="deleteid">确 定</el-button>
				</div>
			</span>
		</el-dialog>
		<!-- 批量删除 -->
		<el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
			<div style="font-size: 16px">确认删除这批数据吗?</div>
			<span slot="footer" style="display: flex; justify-content: space-between" class="dialog-footer">
				<div></div>
				<div>
					<el-button @click="centerDialogVisiblet = false">取 消</el-button>
					<el-button type="primary" @click="deleteid_t">确 定</el-button>
				</div>
			</span>
		</el-dialog>
		<!-- <button @click="fun">你好</button> -->
	</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { scenicList, scenicDele, scenicAdd, sceniceditD } from '../../api/scenicApi/index';
import { scenicUpload } from '../../api/uploading/index'
import { Plus, Search, RefreshRight } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { inject } from 'vue'
const testFn = inject('testFn')
import '../../../style/all.css'//全局css
testFn()
const testName = inject('testName')
// 懒加载函数
const loadTableData = (row, treeNode, resolve) => {
	// 模拟异步请求数据
	setTimeout(() => {
		const data = renders(currentPage.value, pageSize.value);
		// resolve(data.rows[0]);
		console.log(data.rows[0]);
		Data_Imgs.value = data.rows[0]

	}, 1400);
};
const total = ref(0)
const Exass = ref()
const msg = ref('')
const dialogImageUrl = ref('');
const dialogImageUrlt = ref('');
const dialogVisible = ref(false);
const dialogVisiblet = ref(false)
const fileList = ref([]);

// 富文本
const editorConfig = reactive({
	// 编辑器不自动被内容撑高
	autoHeightEnabled: false,
	// 初始容器高度
	initialFrameHeight: 200,
	// 初始容器宽度
	initialFrameWidth: '100vw',
	UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
	serverUrl: '/web/uploads', // 服务端接⼝
	uploadUrl: '/UEditor',
	// enableAutoSave: true, // 开启从草稿箱恢复功能需要⼿动设置固定的 editorId，否则组件会默认随机⼀个，如果页⾯刷新，下次渲染的时候 editorId 会重新随机，// 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
});

// 上传图片返回路径
const fileImg = ref([])
const Delete = ref('')
const fileListst = ref([])
const fileListQW = ref([])
// 照片移除后的数据
const fileremover = ref([])
const fileListqq = ref([])
const status = ref('1')
const iitimg = ref([])

// 图片移除
// 图片移除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
	console.log(uploadFile)
	console.log(uploadFiles)
	const formData = new FormData();
	formData.append('file', uploadFile.raw);
	scenicUpload(formData).then(res => {
		console.log(res.data.url);
		iitimg.value.forEach((item, index) => {
			if (item == testName+ res.data.url) {
				iitimg.value.splice(index, 1)

			}
		})
	})
	// iitimg.value.forEach((item, index) => {
	// 	if (item == uploadFile.url.slice(26, 106)) {
	// 		iitimg.value.splice(index, 1)
	// 	}
	// })

	for (let i = 0; i < iitimg.value.length; i++) {
		if (iitimg.value[i] == uploadFile.url.slice(26, 106)) {
			iitimg.value.splice(iitimg.value[i], 1)
			break;
		}
	}
	console.log(iitimg.value);
}
// 图片放大视图
const handlePictureCardPreview = (file) => {
	// console.log(file.raw.name);
	dialogImageUrl.value = file.url;
	dialogVisible.value = true;
}
const tokens = JSON.parse(localStorage.getItem('tokens'));
const imgList = ref([])
// 图片超出限制
const exceed_li = () => {
	ElMessage({
		message: '最多可上传四张',
		type: 'warning',
	})
}
// 图片上传回调函数
const handleChange = (file, fileLists) => {
	const fileName = file.name
	const fileType = fileName.substring(fileName.lastIndexOf('.'))
	const formData = new FormData();
	formData.append('file', file.raw);
	scenicUpload(formData).then(res => {
		console.log(res.code);
		if (res.code == 1) {
			ruleForm.img = res.data.url
			console.log(res.data, '上传成功');
			fileImg.value.push(res.data.url)
			fileremover.value.push(res.data.url)
			imgList.value.push(res.data.url.split(','))
			iitimg.value.push(res.data.url)
		} else if (res.code == 0) {
			ElMessage.error('图片不能大于2MB!')
			for (let i = 0; i < fileLists.length; i++) {
				if (i === fileLists.length - 1) {
					fileLists.splice(i, 1)
				}
			}
		}
	})
	// }
	// jpeg,.png,.jpg,.bmp,.gif
	if (
		fileType === '.jpg' ||
		fileType === '.png' ||
		fileType === '.jpeg' ||
		fileType === '.bmp' ||
		fileType === '.gif'
	) {
	} else {
		ElMessage.error('不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型')
		return false
	}
	console.log(file);
	console.log(file.raw);




};
// success成功回调函数 图片
const handleSuccess = (response, file, fileList) => {

	console.log('File uploaded successfully:', response, file, fileList);
	console.log(fileImg.value);

};

const beforeUpload = (rawFile) => {
	console.log(rawFile);
	console.log(1);


	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('Avatar picture must be JPG format!')

		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error('Avatar picture size can not exceed 2MB!')

		return false
	}
	return true
}

// 新增封面图片上传总
// 图片放大视图
const fileListt = ref([]);
const handlePictureCardPreviewt = (file) => {
	// console.log(file.raw.name);
	dialogImageUrlt.value = file.url;
	dialogVisiblet.value = true;
}
// 图片移除
const handleRemovet = (file, fileListt) => {
	console.log(file, fileListt);
};
// 图片上传回调事件
const beforeAvatarUploadt = (file) => {
	const fileName = file.name
	const fileType = fileName.substring(fileName.lastIndexOf('.'))
	// jpeg,.png,.jpg,.bmp,.gif
	if (
		fileType === '.jpg' ||
		fileType === '.png' ||
		fileType === '.jpeg' ||
		fileType === '.bmp' ||
		fileType === '.gif'
	) {
	} else {
		ElMessage.error('不是,jpeg,.png,.jpg,.bmp,.gif文件,请上传正确的图片类型')
		return false
	}
	console.log(file);
	// 压缩图片
	compressImage(file).then(compressedBlob => {
		const formData = new FormData();
		formData.append('file', compressedBlob, file.name);
		if (file.size / 1024 / 1024 > 2) {
			console.log(file.size / 1024 / 1024);
			ElMessage.error('图片不能大于2MB!')
			return false
		} else {

			console.log(formData);
			scenicUpload(formData).then(res => {
				console.log(res);

				// fileImg.cover = res.data.url
				fileListt.value = [{
					name: 'plant-1.png',
					url: testName + res.data.url,
				}]
				ruleForm.covers = res.data.url
			})
		}
	});
	return false; // 阻止默认上传行为

}
const compressImage = (file) => {
	const reader = new FileReader();
	reader.readAsDataURL(file);
	return new Promise((resolve) => {
		reader.onload = e => {
			const img = new Image();
			img.src = e.target.result;
			img.onload = () => {
				const canvas = document.createElement('canvas');
				const ctx = canvas.getContext('2d');
				const { width, height } = img;
				canvas.width = width;
				canvas.height = height;
				ctx.drawImage(img, 0, 0, width, height);
				// 可以在这里调整压缩质量和尺寸
				const quality = 0.7; // 压缩质量
				const newImageData = canvas.toDataURL('image/jpeg', quality);
				const resizedBlob = dataURLtoBlob(newImageData);
				console.log(ctx);
				resolve(resizedBlob);
			};
		};
	});
};
const dataURLtoBlob = (dataurl) => {
	const arr = dataurl.split(',');
	const mime = arr[0].match(/:(.*?);/)[1];
	const bstr = atob(arr[1]);
	let n = bstr.length;
	const u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], { type: mime });
};

// 删除批量
// 全选单选
const multipleTableRef = ref()
const SelectArr = ref([])
const All_Delete = ref([])
const handleSelectionChange = (val) => {
	All_Delete.value = []
	SelectArr.value = val
	console.log(SelectArr.value);
	SelectArr.value.forEach(item => {
		console.log(item);
		All_Delete.value.push(item.id)
	})
	console.log(All_Delete.value);
}

// 点击删除出现弹窗
const centerDialogVisible = ref(false);
const titleN = ref('');
const deleteids = ref('')
// 删除批量删除状态
const deleteStatus = ref('')
function deletes(item) {
	centerDialogVisible.value = true;
	titleN.value = item.name;
	deleteids.value = item.id
	deleteStatus.value = '1'
}
// 确认删除
function deleteid() {
	console.log('普通删除');
	scenicDele({
		token: tokens.token,
		uid: tokens.id
	}, {
		ids: deleteids.value,
	}).then(res => {
		console.log(res, '删除成功或失败回调');
		centerDialogVisible.value = false;
		renders()
		ElMessage({
			message: '删除成功',
			type: 'success',
		})
	})
}

const centerDialogVisiblet = ref(false)
const st = ref([])
function deleList() {
	st.value = []
	console.log(All_Delete.value);
	st.value.push(All_Delete.value)
	if (All_Delete.value == '') {
		ElMessage({
			message: '请勾选要删除的景点',
			type: 'warning',
		})
	} else {
		centerDialogVisiblet.value = true
	}
}
// 确认批量删除
const deleteid_t = () => {
	scenicDele({
		token: tokens.token,
		uid: tokens.id
	}, {
		ids: st.value.join(','),
	}).then(res => {
		console.log(res, '删除成功或失败回调');
		centerDialogVisiblet.value = false;
		renders()
		ElMessage({
			message: '删除成功',
			type: 'success',
		})
	})
}

// 输入框
const search = ref('')

// 请求景点列表
// 列表数据
const scenic_list = ref([])
const arrlist = ref([])
const imgSlice = ref([])
const Data_Img = ref([])
const Data_Imgs = ref([])

renders()
function renders(page, pageSize) {
	scenicList({
		token: tokens.token,
		uid: tokens.id
	}).then(res => {
		scenic_list.value = res.data
		arrlist.value = res.data


		if (Data_Img.value.length > 0) {
			Data_Img.value = []
		}
		res.data.forEach(item => {

			Data_Img.value.push({
				...item,
				image: item.imgs.split(',')[0],
				// banner: item.imgs.split(',')
			})
			Data_Imgs.value.push({
				...item,
				image: item.imgs.split(',')[0],
				// banner: item.imgs.split(',')
			})
		});
		console.log(Data_Img.value);
	})
	// 模拟从服务器获取数据
	total.value = 30; // 假设总共有1000条数据
	const rows = [];
	for (let i = (page - 1) * pageSize; i < page * pageSize && i < total.value; i++) {
		rows.push(arrlist.value);


	}
	return { total, rows };
}
// 点击查询
const searchs = () => {
	Data_Img.value = Data_Imgs.value.filter(function (item) {
		// 判断是否满足搜索条件
		if (String(item.name).indexOf(String(search.value)) > -1
		) {
			return Data_Img
		}
	})
	currentPage.value = 1
}
// 点击重置
const resets = () => {
	search.value = ''
	renders()
}
// input事件
const filterg = () => {

}

// 表格页码数
const pageSize = ref(5);
const currentPage = ref(1);
// 新增编辑title动态
const disableds = ref(true);
// 点击新增或确认做判断
const statusAdd = ref('');
// 点击新增
function add() {
	statusAdd.value = '1'
	dialogTableVisible.value = true
	disableds.value = true
}
const dialogTableVisible = ref(false);
// 新增输入框响应值
const ruleForm = reactive({
	idtitle: '',
	name: '',
	introduce: '',
	img: '',
	covers: ''
});
// 编辑所用id
const editDataid = ref('')
// 点击编辑
function edit(item) {
	status.value = '2'
	console.log(item);
	statusAdd.value = '2'
	editDataid.value = item.id
	ruleForm.name = item.name;
	ruleForm.introduce = item.introduce;
	dialogTableVisible.value = true;
	disableds.value = false;
	iitimg.value = item.imgs.split(',')

	Delete.value = item.imgs
	console.log(item.imgs.split(',')[0]);
	if (fileremover.value == '') {
		fileremover.value = item.imgs.split(',')
	}
	// console.log(item.banner.join(''));
	// if(item){
	// }
	// 封面图片回显
	fileListt.value = [{
		url: testName + item.cover,
	}]
	for (let i = 0; i < item.imgs.split(',').length; i++) {
		console.log(item.imgs.split(','));
		fileListQW.value.push(testName + item.imgs.split(',')[i])
		fileList.value.push(
			{
				url: testName + item.imgs.split(',')[i],
			});
	}
	console.log(item.imgs.split(','));
	fileImg.value = item.imgs.split(',')
	// fileImg.value = item.imgs

	ruleForm.img = item.imgs
	ruleForm.covers = item.cover

	// }

	// }
}

// 关闭新增
const close = (formEl) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleForm.name = '';
	ruleForm.introduce = '';
	fileList.value = [];
	fileImg.value = []
	ruleForm.img = ''
	ruleForm.covers = ''
	fileListt.value = ''
	status.value = '1'
	// document.getElementById('exttas').style='display:none'

};
// 关闭新增
const closes = (formEl) => {
	if (!formEl) return;
	formEl.resetFields();
	dialogTableVisible.value = false;
	fileListt.value = '';
	status.value = '1';

	// fileImg.value=[]
};
// 表单效验集合
const ruleFormRef = ref();
const validatePass = (rule, value, callback) => {
	if (value === '') {
		callback(new Error('Please input the password'));
	} else {
		if (ruleForm.checkPass !== '') {
			if (!ruleFormRef.value) return;
			ruleFormRef.value.validateField('checkPass', () => null);
		}
		callback();
	}
};
// 新增输入框判断效验
const rules = reactive({
	name: [{ required: true, message: '请输入景点名称', trigger: 'blur' }],
	introduce: [{ required: true, message: '请输入景点介绍', trigger: 'blur' }],
	img: [{ required: true, message: '请上传图片', trigger: 'blur' }],
	covers: [{ required: true, message: '请上传封面图片', trigger: 'blur' }]

});
// 点击新增确认
const submitForm = (formEl) => {
	console.log(ruleForm);

	// if(fileImg.value==''){
	// 	document.getElementById('exttas').style='display:block'
	// }else{
	// 	document.getElementById('exttas').style='display:none'

	// }
	if (!formEl) return;
	formEl.validate((valid) => {
		if (valid) {
			// 效验通过执行
			console.log('submit!');
			if (statusAdd.value == '1') {
				console.log(fileImg.value);
				console.log(imgList.value.length);
				if (iitimg.value.length < 3) {
					ElMessage({
						message: '最少上传三张景点图片',
						type: 'warning',
					})
				} else if (iitimg.value.length > 5) {
					ElMessage({
						message: '最多上传四张景点图片',
						type: 'warning',
					})

				} else {
					scenicAdd({
						name: ruleForm.name,
						introduce: ruleForm.introduce,
						imgs: iitimg.value.join(','),
						cover: ruleForm.covers
					}, {
						token: tokens.token,
						uid: tokens.id
					}).then(res => {
						console.log(res);
						dialogTableVisible.value = false;

						renders()
						ElMessage({
							message: '新增成功',
							type: 'success',
						})
					})
				}
			} else if (statusAdd.value == '2') {
				// handleChange()
				console.log(iitimg.value);
				if (iitimg.value.length < 3) {
					ElMessage({
						message: '最少上传三张景点图片',
						type: 'warning',
					})
				} else if (iitimg.value.length > 5) {
					ElMessage({
						message: '最多上传四张景点图片',
						type: 'warning',
					})

				} else {

					sceniceditD({
						id: editDataid.value,
						name: ruleForm.name,
						introduce: ruleForm.introduce,
						imgs: iitimg.value.join(','),
						cover: ruleForm.covers
						// image:fileImg.value	
					}, {
						token: tokens.token,
						uid: tokens.id
					}).then(res => {
						console.log(res);
						// dialogTableVisible.value = false;
						renders()
						if (res.code == 0) {
							ElMessage({
								message: '操作失败,不能与原数据一致',
								type: 'warning',
							})
						} else {
							dialogTableVisible.value = false;

							ElMessage({
								message: '编辑成功',
								type: 'success',
							})
						}

					})


				}




			}
		} else {
			console.log('error submit!');
			console.log(fileImg.value);
			ElMessage.error('新增失败')
			return false;
		}
	});
}


</script>

<style scoped>
#exttas {
	margin-left: 80px;
	margin-top: -16px;
	color: red;
	font-size: 12px;
	display: none;
}

.demonstration {
	color: var(--el-text-color-secondary);
}

.el-carousel__item h3 {
	/* color: #475669; */
	opacity: 0.75;
	/* line-height: 150px; */
	margin: 0;
	text-align: center;
}



.paging {
	display: flex;
	justify-content: center;
	margin-top: 10px;
}

/* 搜索一行div弹性 */
.search_row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 10px;
}
</style>